class IDGenerator {
    constructor() {
        // 移除 constructor 中的 DOMContentLoaded 监听
        this.initializeUI();
        this.setupEventListeners();
        this.loadHistory();
    }

    initializeUI() {
        // 检查 areaData 是否存在
        if (typeof areaData === 'undefined') {
            console.error('地区数据未加载，请确保 area-data.js 已正确引入');
            return;
        }

        // 初始化省份选择器
        const provinceSelect = document.getElementById('province');
        provinceSelect.innerHTML = '<option value="" disabled>请选择省份</option>';
        for (const [code, name] of Object.entries(areaData.provinces)) {
            const option = document.createElement('option');
            option.value = code;
            option.textContent = name;
            provinceSelect.appendChild(option);
        }
        // 设置默认省份（北京市）
        provinceSelect.value = '11';

        // 初始化城市选择器并设置默认值
        const citySelect = document.getElementById('city');
        citySelect.innerHTML = '<option value="" disabled>请选择城市</option>';
        const cities = areaData.cities['11'] || {};
        for (const [code, name] of Object.entries(cities)) {
            const option = document.createElement('option');
            option.value = code;
            option.textContent = name;
            citySelect.appendChild(option);
        }
        // 设置默认城市（市辖区）
        citySelect.value = '01';

        // 初始化区县选择器并设置默认值
        const districtSelect = document.getElementById('district');
        districtSelect.innerHTML = '<option value="" disabled>请选择区县</option>';
        const districts = areaData.districts['1101'] || {};
        for (const [code, name] of Object.entries(districts)) {
            const option = document.createElement('option');
            option.value = code.padStart(2, '0');
            option.textContent = name;
            districtSelect.appendChild(option);
        }
        // 设置默认区县（东城区）
        districtSelect.value = '01';

        // 设置默认日期
        const defaultDate = `2000-01-01`;
        document.getElementById('birthDate').value = defaultDate;
    }

    setupEventListeners() {
        // 省份变化时更新城市
        document.getElementById('province').addEventListener('change', () => this.updateCities());
        // 城市变化时更新区县
        document.getElementById('city').addEventListener('change', () => this.updateDistricts());
        
        // 移除不存在的年月日选择器的事件监听
        // document.getElementById('year').addEventListener('change', () => this.updateDays());
        // document.getElementById('month').addEventListener('change', () => this.updateDays());
        
        // 生成按钮点击事件
        document.getElementById('generate').addEventListener('click', () => this.generateID());
        // 复制按钮点击事件
        document.getElementById('copy').addEventListener('click', () => this.copyToClipboard());
        // 添加清除历史记录事件
        document.getElementById('clearHistory').addEventListener('click', () => this.clearHistory());
        // 添加批量生成事件监听
        document.getElementById('batchGenerate').addEventListener('click', () => this.batchGenerateIDs());
        
        // 添加数量输入限制
        const batchInput = document.getElementById('batchCount');
        batchInput.addEventListener('input', (e) => {
            let value = parseInt(e.target.value);
            if (value < 1) e.target.value = 1;
            if (value > 100) e.target.value = 100;
        });

        // 添加日期输入验证
        document.getElementById('birthDate').addEventListener('input', (e) => this.validateDate(e.target));
    }

    updateCities() {
        const provinceCode = document.getElementById('province').value;
        const citySelect = document.getElementById('city');
        citySelect.innerHTML = '';
        
        const cities = areaData.cities[provinceCode] || {};
        for (const [code, name] of Object.entries(cities)) {
            const option = document.createElement('option');
            option.value = code;
            option.textContent = name;
            citySelect.appendChild(option);
        }

        this.updateDistricts();
    }

    updateDistricts() {
        const provinceCode = document.getElementById('province').value;
        const cityCode = document.getElementById('city').value;
        const districtSelect = document.getElementById('district');
        districtSelect.innerHTML = '';
        
        const districts = areaData.districts[provinceCode + cityCode] || {};
        for (const [code, name] of Object.entries(districts)) {
            const option = document.createElement('option');
            // 确保区县代码是两位数
            option.value = code.padStart(2, '0');
            option.textContent = name;
            districtSelect.appendChild(option);
        }
    }

    updateDays() {
        const year = parseInt(document.getElementById('year').value) || 2000;
        const month = parseInt(document.getElementById('month').value) || 1;
        const daySelect = document.getElementById('day');
        const currentDay = daySelect.value;
        daySelect.innerHTML = '<option value="" disabled>日</option>';

        const daysInMonth = new Date(year, month, 0).getDate();
        for (let day = 1; day <= daysInMonth; day++) {
            const option = document.createElement('option');
            option.value = day.toString().padStart(2, '0');
            option.textContent = day + '日';
            daySelect.appendChild(option);
        }

        // 如果之前选择的日期在新的月份中有效，则保持选择
        // 否则设置为1日
        if (currentDay && parseInt(currentDay) <= daysInMonth) {
            daySelect.value = currentDay;
        } else {
            daySelect.value = '01';
        }
    }

    generateID() {
        try {
            const count = parseInt(document.getElementById('batchCount').value) || 1;
            const ids = [];

            for (let i = 0; i < count; i++) {
                const provinceCode = document.getElementById('province').value;
                const cityCode = document.getElementById('city').value;
                const districtCode = document.getElementById('district').value;
                
                // 组合成6位区域代码
                const areaCode = provinceCode + cityCode + districtCode;
                if (!areaCode || areaCode.length !== 6) {
                    throw new Error('请选择完整的地区信息');
                }

                const birthDate = document.getElementById('birthDate').value;
                if (!birthDate) {
                    throw new Error('请输入出生日期');
                }
                
                // 统一分隔符并获取日期部分
                const normalizedDate = birthDate.replace(/\//g, '-');
                const [year, month, day] = normalizedDate.split('-');
                
                const gender = document.querySelector('input[name="gender"]:checked').value;
                
                // 生成3位顺序码（保证性别）
                let sequenceNum = Math.floor(Math.random() * 999);
                if (gender === '1') { // 男性
                    if (sequenceNum % 2 === 0) sequenceNum += 1;
                } else { // 女性
                    if (sequenceNum % 2 === 1) sequenceNum += 1;
                }
                const sequence = sequenceNum.toString().padStart(3, '0');

                const id17 = `${areaCode}${year}${month}${day}${sequence}`;
                const checkCode = this.calculateCheckCode(id17);
                if (!checkCode) {
                    throw new Error('校验码生成失败');
                }
                
                const fullID = id17 + checkCode;
                ids.push(fullID);
                this.addToHistory(fullID);
            }

            // 显示所有生成的号码
            document.getElementById('idNumber').value = ids.join('\n');
        } catch (error) {
            console.error('生成身份证号失败:', error);
            document.getElementById('idNumber').value = '生成失败: ' + error.message;
        }
    }

    calculateCheckCode(id17) {
        try {
            if (id17.length !== 17) {
                throw new Error('身份证号前17位长度错误');
            }

            const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
            const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
            
            let sum = 0;
            for (let i = 0; i < 17; i++) {
                const num = parseInt(id17[i]);
                if (isNaN(num)) {
                    throw new Error('身份证号包含非数字字符');
                }
                sum += num * weights[i];
            }
            
            return checkCodes[sum % 11];
        } catch (error) {
            console.error('计算校验码失败:', error);
            return null;
        }
    }

    copyToClipboard() {
        const idNumber = document.getElementById('idNumber');
        idNumber.select();
        document.execCommand('copy');
        
        const copyBtn = document.getElementById('copy');
        const originalText = copyBtn.textContent;
        copyBtn.textContent = '已复制！';
        setTimeout(() => {
            copyBtn.textContent = originalText;
        }, 2000);
    }

    addToHistory(id) {
        const historyList = document.getElementById('historyList');
        const li = document.createElement('li');
        li.textContent = id;
        
        if (historyList.children.length >= 10) {
            historyList.removeChild(historyList.lastChild);
        }
        
        historyList.insertBefore(li, historyList.firstChild);
        this.saveHistory();
    }

    loadHistory() {
        const history = JSON.parse(localStorage.getItem('idGeneratorHistory') || '[]');
        const historyList = document.getElementById('historyList');
        history.forEach(id => {
            const li = document.createElement('li');
            li.textContent = id;
            historyList.appendChild(li);
        });
    }

    saveHistory() {
        const historyList = document.getElementById('historyList');
        const history = Array.from(historyList.children).map(li => li.textContent);
        localStorage.setItem('idGeneratorHistory', JSON.stringify(history));
    }

    clearHistory() {
        const historyList = document.getElementById('historyList');
        historyList.innerHTML = '';
        localStorage.removeItem('idGeneratorHistory');
        
        // 添加清除动画效果
        const clearBtn = document.getElementById('clearHistory');
        clearBtn.classList.add('rotating');
        setTimeout(() => {
            clearBtn.classList.remove('rotating');
        }, 500);
    }

    // 添加一个随机日期生成方法
    getRandomDate() {
        const startYear = 1950;
        const endYear = new Date().getFullYear() - 1;
        const year = Math.floor(Math.random() * (endYear - startYear + 1)) + startYear;
        const month = (Math.floor(Math.random() * 12) + 1).toString().padStart(2, '0');
        const daysInMonth = new Date(year, month, 0).getDate();
        const day = Math.floor(Math.random() * daysInMonth + 1).toString().padStart(2, '0');
        
        return {
            year: year.toString(),
            month,
            day
        };
    }

    // 修改随机地区生成方法
    getRandomArea() {
        try {
            // 获取所有省份代码
            const provinceCodes = Object.keys(areaData.provinces);
            const provinceCode = provinceCodes[Math.floor(Math.random() * provinceCodes.length)];
            
            // 获取选中省份的所有城市代码
            const cities = areaData.cities[provinceCode] || {};
            const cityCodes = Object.keys(cities);
            if (cityCodes.length === 0) {
                // 如果没有城市数据，使用默认值
                return {
                    provinceCode: "11",
                    cityCode: "01",
                    districtCode: "01"
                };
            }
            const cityCode = cityCodes[Math.floor(Math.random() * cityCodes.length)];
            
            // 获取选中城市的所有区县代码
            const districts = areaData.districts[provinceCode + cityCode] || {};
            const districtCodes = Object.keys(districts);
            if (districtCodes.length === 0) {
                // 如果没有区县数据，使用默认值
                return {
                    provinceCode,
                    cityCode,
                    districtCode: "01"
                };
            }
            const districtCode = districtCodes[Math.floor(Math.random() * districtCodes.length)];
            
            return {
                provinceCode,
                cityCode,
                districtCode: districtCode.padStart(2, '0')
            };
        } catch (error) {
            console.error('随机地区生成失败，使用默认值:', error);
            // 返回北京市东城区作为默认值
            return {
                provinceCode: "11",
                cityCode: "01",
                districtCode: "01"
            };
        }
    }

    // 修改批量生成方法
    batchGenerateIDs() {
        try {
            const count = parseInt(document.getElementById('batchCount').value) || 1;
            const ids = [];
            const gender = document.querySelector('input[name="gender"]:checked').value;

            // 生成指定数量的身份证号
            for (let i = 0; i < count; i++) {
                // 随机生成地区
                const area = this.getRandomArea();
                const areaCode = area.provinceCode + area.cityCode + area.districtCode;
                
                // 随机生成日期
                const date = this.getRandomDate();
                
                // 生成随机序列号
                let sequenceNum = Math.floor(Math.random() * 999);
                if (gender === '1') { // 男性
                    if (sequenceNum % 2 === 0) sequenceNum += 1;
                } else { // 女性
                    if (sequenceNum % 2 === 1) sequenceNum += 1;
                }
                const sequence = sequenceNum.toString().padStart(3, '0');
                
                const id17 = `${areaCode}${date.year}${date.month}${date.day}${sequence}`;
                const checkCode = this.calculateCheckCode(id17);
                if (!checkCode) {
                    throw new Error('校验码生成失败');
                }
                
                const fullID = id17 + checkCode;
                ids.push(fullID);
                this.addToHistory(fullID);
            }

            // 显示所有生成的号码
            document.getElementById('idNumber').value = ids.join('\n');
            
        } catch (error) {
            console.error('生成身份证号失败:', error);
            document.getElementById('idNumber').value = '生成失败: ' + error.message;
        }
    }

    // 日期验证方法
    validateDate(input) {
        const value = input.value;
        if (!value) return;

        // 统一分隔符为 -
        const normalizedDate = value.replace(/\//g, '-');
        const parts = normalizedDate.split('-');
        
        if (parts.length === 3) {
            const year = parseInt(parts[0]);
            const month = parseInt(parts[1]);
            const day = parseInt(parts[2]);
            
            // 检查年份范围
            const currentYear = new Date().getFullYear();
            if (year < 1900 || year > currentYear) {
                input.setCustomValidity('年份必须在1900年到当前年份之间');
                return;
            }
            
            // 检查日期是否有效
            const date = new Date(year, month - 1, day);
            const isValid = date.getFullYear() === year &&
                          date.getMonth() === month - 1 &&
                          date.getDate() === day;
            
            if (!isValid) {
                input.setCustomValidity('请输入有效的日期');
            } else {
                input.setCustomValidity('');
            }
        }
    }
}

// 主题切换功能
class ThemeManager {
    static init() {
        const themeToggle = document.getElementById('themeToggle');
        const body = document.body;
        
        // 加载保存的主题设置
        const isDarkMode = localStorage.getItem('darkMode') === 'true';
        if (isDarkMode) {
            body.classList.add('dark-mode');
            themeToggle.textContent = '🌞';
        }
        
        // 添加切换事件
        themeToggle.addEventListener('click', () => {
            body.classList.toggle('dark-mode');
            const isDark = body.classList.contains('dark-mode');
            themeToggle.textContent = isDark ? '🌞' : '🌓';
            localStorage.setItem('darkMode', isDark);
        });
    }
}

// 确保在 DOM 和所有脚本加载完成后再初始化
window.addEventListener('load', () => {
    if (typeof areaData === 'undefined') {
        console.error('地区数据未加载，请确保 area-data.js 已正确引入');
        return;
    }
    new IDGenerator();
    ThemeManager.init();
}); 